<script setup>
import { useScroll } from '@vueuse/core'
import { onBeforeUpdate, ref, watch } from 'vue'
import myMenu from '../../menu/index.vue'
import { useStore } from 'vuex'

const store = useStore()

const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '60px'
})

const currentCategoryIndex = ref(0)

let itemsRef = []
const setItemRef = (el) => {
  if (el) {
    itemsRef.push(el)
  }
}
//当数据发生改变时，DOM变化之前清空了items
onBeforeUpdate(() => {
  itemsRef = []
})

const ulTarget = ref(null)

const { x: ulScrollLeft } = useScroll(ulTarget)

watch(currentCategoryIndex, (val) => {
  const { left, width } = itemsRef[val].getBoundingClientRect()
  sliderStyle.value = {
    transform: `translateX(${ulScrollLeft.value + left - 10}px)`,
    width: width + 'px'
  }
})

const onItemClick = (index) => {
  currentCategoryIndex.value = index
}

//定义popup的初始值
const isOpenPopup = ref(false)

const doShowPopup = () => {
  isOpenPopup.value = true
}
</script>

<template>
  <div class="bg-white dark:bg-zinc-900 sticky top-0 left-0 z-10">
    <ul
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
      style="list-style-type: none"
    >
      <!-- 滑块 strat -->

      <li
        ref="sliderTarget"
        :style="sliderStyle"
        class="absolute h-[22px] bg-zinc-900 rounded-lg duration-200 dark:bg-zinc-800"
      ></li>

      <!-- 滑块 end -->

      <li
        class="fixed top-0 right-[-1px] h-4 px-1 flex items-center bg-white z-20 dark:bg-zinc-900 shadow-l-white dark:shadow-l-zinc"
        @click="doShowPopup"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="list"></m-svg-icon>
      </li>
      <li
        v-for="(item, index) in $store.getters.categorys"
        :key="item.name"
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
        :ref="setItemRef"
        @click="onItemClick(index)"
        :class="{
          'text-zinc-100': currentCategoryIndex === index
        }"
      >
        {{ item.username }}
      </li>
    </ul>
    <m-popup v-model="isOpenPopup">
      <myMenu @onItemClick="onItemClick"></myMenu>
    </m-popup>
  </div>
</template>

<style lang="scss" scoped></style>
